"use client"

import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Platform, Image } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { Book, Calendar } from "lucide-react-native"
import { useRouter, useFocusEffect } from "expo-router"
import { useState, useCallback } from "react"
import { theme } from "../../constants/theme"
import AsyncStorage from "@react-native-async-storage/async-storage"
// 更新导入路径，从 components/plan/create-plan-modal 导入
import { CreatePlanModal } from "../../components/plan/create-plan-modal"
import { BookPlanCard } from "../../components/plan/BookPlanCard"
import { TodayPlanSection } from "../../components/plan/TodayPlanSection"
import { PlanTimeline } from "../../components/plan/PlanTimeline"

// 默认书本数据
const DEFAULT_BOOK = {
    id: "default",
    title: "人教版英语",
    subtitle: "七年级上册",
    mastered: 0,
    learning: 0,
    total: 448,
    coverImage: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png",
    color: "#5B8EF4",
}

// 默认计划数据
const DEFAULT_PLAN_DAYS = [
    { day: 1, status: "进行中", newWords: 3, reviewWords: 0 },
    { day: 2, status: "未开始", newWords: 3, reviewWords: 3 },
    { day: 3, status: "未开始", newWords: 3, reviewWords: 6 },
]

// 默认今日计划
const DEFAULT_TODAY_PLAN = {
    newWords: { count: 1, status: "未完成" },
    reviewWords: { count: 0, status: "已完成" },
}

export default function PlanScreen() {
    const router = useRouter()
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [currentBook, setCurrentBook] = useState(DEFAULT_BOOK)
    const [bookPlans, setBookPlans] = useState({})
    const [hasPlans, setHasPlans] = useState(false)
    const [todayPlan, setTodayPlan] = useState(DEFAULT_TODAY_PLAN)
    const [planDays, setPlanDays] = useState(DEFAULT_PLAN_DAYS)

    // 使用 useFocusEffect 确保每次页面获得焦点时都检查是否有新的书籍数据
    useFocusEffect(
        useCallback(() => {
            const loadSelectedPlanBook = async () => {
                try {
                    const bookData = await AsyncStorage.getItem("selectedPlanBook")
                    if (bookData) {
                        const selectedBook = JSON.parse(bookData)
                        console.log("加载选中的计划书籍:", selectedBook)

                        // 更新当前书本
                        setCurrentBook({
                            id: selectedBook.id,
                            title: selectedBook.title,
                            subtitle: selectedBook.subtitle,
                            mastered: selectedBook.mastered || 0,
                            learning: selectedBook.learning || 0,
                            total: selectedBook.total,
                            coverImage: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png",
                            color: "#5B8EF4",
                        })

                        // 加载该书本对应的计划
                        loadBookPlans(selectedBook.id)
                    }
                } catch (error) {
                    console.error("读取选中计划书籍数据失败:", error)
                }
            }

            loadSelectedPlanBook()
        }, []),
    )

    // 加载书本对应的计划
    const loadBookPlans = async (bookId) => {
        try {
            // 获取当前活跃的书本ID
            const plansData = await AsyncStorage.getItem(`plans_${bookId}`)
            if (plansData) {
                const plans = JSON.parse(plansData)
                setBookPlans((prev) => ({
                    ...prev,
                    [bookId]: plans,
                }))
                setHasPlans(plans.length > 0)

                // 如果有计划，更新今日计划和计划天数
                if (plans.length > 0) {
                    const currentPlan = plans[0]
                    // 设置今日计划数据
                    setTodayPlan({
                        newWords: {
                            count: currentPlan.dailyNewWords || 1,
                            status: "未完成",
                        },
                        reviewWords: {
                            count: currentPlan.currentDay > 1 ? (currentPlan.currentDay - 1) * currentPlan.dailyNewWords : 0,
                            status: "已完成",
                        },
                    })

                    // 设置计划天数数据
                    const planDaysData = []
                    for (let i = 0; i < 3; i++) {
                        const day = currentPlan.currentDay + i
                        const reviewCount = day > 1 ? (day - 1) * currentPlan.dailyNewWords : 0
                        planDaysData.push({
                            day: day,
                            status: i === 0 ? "进行中" : "未开始",
                            newWords: currentPlan.dailyNewWords,
                            reviewWords: reviewCount,
                        })
                    }
                    setPlanDays(planDaysData)
                } else {
                    // 如果没有计划，使用默认值
                    setTodayPlan(DEFAULT_TODAY_PLAN)
                    setPlanDays(DEFAULT_PLAN_DAYS)
                }
            } else {
                setHasPlans(false)
                // 如果没有计划，使用默认值
                setTodayPlan(DEFAULT_TODAY_PLAN)
                setPlanDays(DEFAULT_PLAN_DAYS)
            }
        } catch (error) {
            console.error("读取书本计划数据失败:", error)
            setHasPlans(false)
            // 如果出错，使用默认值
            setTodayPlan(DEFAULT_TODAY_PLAN)
            setPlanDays(DEFAULT_PLAN_DAYS)
        }
    }

    // Update the saveBookPlan function to only allow one plan per book
    const saveBookPlan = async (bookId, plan) => {
        try {
            // Simply overwrite any existing plan
            await AsyncStorage.setItem(`plans_${bookId}`, JSON.stringify([plan]))

            setBookPlans((prev) => ({
                ...prev,
                [bookId]: [plan],
            }))

            setHasPlans(true)
            setIsModalVisible(false) // Close modal after saving
        } catch (error) {
            console.error("保存书本计划数据失败:", error)
        }
    }

    const handleSwitchTextbook = () => {
        router.push({
            pathname: "/books-screen",
            params: { source: "plan", mode: "select_plan_book" },
        })
    }

    // 更新handlePlanList函数，确保正确导航到plan-list-screen
    const handlePlanList = () => {
        router.push("/plan/plan-list-screen")
    }

    const handleLearningDetails = () => {
        router.push("/learning-details-screen")
    }

    // Update the handleCreatePlan function to match the new plan structure
    const handleCreatePlan = (data) => {
        const newPlan = {
            id: Date.now().toString(),
            bookId: currentBook.id,
            dailyNewWords: data.dailyNewWords,
            dailyPlans: data.dailyPlans,
            currentDay: 1,
            progress: 0,
        }

        saveBookPlan(currentBook.id, newPlan)
    }

    const handleLearnPress = () => {
        router.push("/new-learning-screen?mode=new")
    }

    const handleReviewPress = () => {
        console.log(123)
        router.push("/new-learning-screen?mode=review")
    }

    const handleDeletePlan = async () => {
        try {
            await AsyncStorage.removeItem(`plans_${currentBook.id}`)
            setBookPlans((prev) => {
                const newPlans = { ...prev }
                delete newPlans[currentBook.id]
                return newPlans
            })
            setHasPlans(false)
            setTodayPlan(DEFAULT_TODAY_PLAN)
            setPlanDays(DEFAULT_PLAN_DAYS)
            setIsModalVisible(false) // 关闭模态窗口
        } catch (error) {
            console.error("删除计划失败:", error)
        }
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 页面标题 */}
                <View style={styles.header}>
                    <Text style={styles.headerTitle}>学习计划</Text>
                    <TouchableOpacity style={styles.planListButton} onPress={() => router.push("/plan")}>
                        <Calendar size={20} color={theme.colors.primary.default} />
                        <Text style={styles.planListText}>计划列表</Text>
                    </TouchableOpacity>
                </View>

                {/* 导航按钮 */}
                <View style={styles.topNav}>
                    <TouchableOpacity style={styles.navButtonPrimary} onPress={handlePlanList}>
                        <LinearGradient
                            colors={theme.colors.primary.gradient}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 0 }}
                            style={styles.navButtonPrimaryGradient}
                        >
                            <Calendar size={18} color={theme.colors.neutral.white} />
                            <Text style={styles.navButtonPrimaryText}>计划列表</Text>
                        </LinearGradient>
                    </TouchableOpacity>

                    <TouchableOpacity style={styles.navButtonSecondary} onPress={handleSwitchTextbook}>
                        <Book size={18} color={theme.colors.primary.default} />
                        <Text style={styles.navButtonSecondaryText}>切换教材</Text>
                    </TouchableOpacity>
                </View>

                <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
                    {/* 书本卡片 */}
                    <BookPlanCard book={currentBook} onDetailsPress={handleLearningDetails} />

                    {/* 我的计划部分 */}
                    <View style={styles.planSection}>
                        {hasPlans ? (
                            <>
                                {/* 今日计划 */}
                                <TodayPlanSection
                                    todayPlan={todayPlan}
                                    onAdjustPlan={() => setIsModalVisible(true)}
                                    onLearnPress={handleLearnPress}
                                    onReviewPress={handleReviewPress}
                                />

                                {/* 学习计划 */}
                                <PlanTimeline title="学习计划" description="艾宾浩斯记忆法，可以极大地提高记忆效率。" days={planDays} />
                            </>
                        ) : (
                            <View style={styles.emptyPlan}>
                                <Image
                                    source={{ uri: "https://cdn-icons-png.flaticon.com/512/4076/4076478.png" }}
                                    style={styles.emptyImage}
                                />
                                <Text style={styles.emptyTitle}>还没有学习计划</Text>
                                <Text style={styles.emptyText}>为当前教材创建一个学习计划，科学安排每日学习内容，提高记忆效率</Text>
                                <TouchableOpacity style={styles.createButton} onPress={() => setIsModalVisible(true)}>
                                    <LinearGradient
                                        colors={theme.colors.primary.gradient}
                                        start={{ x: 0, y: 0 }}
                                        end={{ x: 1, y: 0 }}
                                        style={styles.createButtonGradient}
                                    >
                                        <Calendar size={18} color={theme.colors.neutral.white} />
                                        <Text style={styles.createButtonText}>创建学习计划</Text>
                                    </LinearGradient>
                                </TouchableOpacity>
                            </View>
                        )}
                    </View>

                    {/* 底部装饰 */}
                    <View style={styles.bottomDecoration}>
                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135789.png" }}
                            style={styles.bottomDecorationImage}
                        />
                    </View>
                </ScrollView>

                <CreatePlanModal
                    visible={isModalVisible}
                    onClose={() => setIsModalVisible(false)}
                    onSubmit={handleCreatePlan}
                    onDelete={handleDeletePlan}
                    currentBook={currentBook}
                    hasExistingPlan={hasPlans}
                />
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingTop: theme.spacing.lg,
        paddingBottom: theme.spacing.md,
    },
    headerTitle: {
        fontSize: theme.fontSize.xxl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    headerAvatar: {
        width: 40,
        height: 40,
        borderRadius: 20,
        borderWidth: 2,
        borderColor: theme.colors.primary.light,
    },
    topNav: {
        flexDirection: "row",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: theme.spacing.lg,
    },
    navButtonPrimary: {
        flex: 1,
        marginRight: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    navButtonPrimaryGradient: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        paddingVertical: theme.spacing.md,
        paddingHorizontal: theme.spacing.lg,
    },
    navButtonPrimaryText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
        marginLeft: theme.spacing.sm,
    },
    navButtonSecondary: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: theme.colors.neutral.white,
        paddingVertical: theme.spacing.md,
        paddingHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        borderWidth: 1,
        borderColor: `${theme.colors.primary.default}30`,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.light,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.1,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    navButtonSecondaryText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.medium,
        color: theme.colors.primary.default,
        marginLeft: theme.spacing.sm,
    },
    scrollView: {
        flex: 1,
    },
    planSection: {
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: theme.spacing.xl,
        gap: theme.spacing.xl,
    },
    bottomDecoration: {
        alignItems: "center",
        marginBottom: theme.spacing.xxxl,
        opacity: 0.5,
    },
    bottomDecorationImage: {
        width: 60,
        height: 60,
    },
    emptyPlan: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        alignItems: "center",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.transparent.black.light,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.15,
                shadowRadius: 10,
            },
            android: {
                elevation: 3,
            },
        }),
    },
    emptyImage: {
        width: 120,
        height: 120,
        marginBottom: theme.spacing.lg,
    },
    emptyTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
    },
    emptyText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginBottom: theme.spacing.xl,
        textAlign: "center",
    },
    createButton: {
        width: "100%",
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    createButtonGradient: {
        flexDirection: "row",
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    createButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        marginLeft: theme.spacing.sm,
    },
    planListButton: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: theme.colors.primary.light + "20",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.xs,
        borderRadius: theme.borderRadius.medium,
    },
    planListText: {
        marginLeft: theme.spacing.xs,
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.medium,
        color: theme.colors.primary.default,
    },
})

